package me.stone.stanimeclient.core.data.local

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.SharedPreferencesMigration
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import me.stone.stanimeclient.core.data.local.DataStoreAppPreferenceStorage.PreferencesKeys.PREF_THEME
import me.stone.stanimeclient.core.model.DarkThemeMode
import javax.inject.Inject
import javax.inject.Singleton

interface AppPreferenceStorage {
    val darkThemeMode: Flow<DarkThemeMode>
    suspend fun updateDarkThemeMode(mode: DarkThemeMode)
}


@Singleton
class DataStoreAppPreferenceStorage @Inject constructor(
    private val dataStore: DataStore<Preferences>
) : AppPreferenceStorage {

    companion object {
        const val PREFS_NAME = "STAClient-Prefs"
    }

    object PreferencesKeys {
        val PREF_THEME = stringPreferencesKey("pref_dark_theme_mode")
    }

    override val darkThemeMode: Flow<DarkThemeMode>
        get() = dataStore.data.map { DarkThemeMode.find(it[PREF_THEME]) }

    override suspend fun updateDarkThemeMode(mode: DarkThemeMode) {
        dataStore.edit {
            it[PREF_THEME] = mode.storageKey
        }
    }

}


@Module
@InstallIn(SingletonComponent::class)
object AppDataStoreModule {

    private val Context.dataStore by preferencesDataStore(
        name = DataStoreAppPreferenceStorage.PREFS_NAME,
        produceMigrations = { context ->
            listOf(
                SharedPreferencesMigration(
                    context,
                    DataStoreAppPreferenceStorage.PREFS_NAME
                )
            )
        }
    )

    @Singleton
    @Provides
    fun providePreferenceStorage(@ApplicationContext context: Context): AppPreferenceStorage =
        DataStoreAppPreferenceStorage(context.dataStore)

}